package server;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by swootton on 27/02/14.
 */
public class SettingsServlet extends MFHttpServlet {

    private Connection connection;

    public SettingsServlet(){

    }


    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("SettingsServlet.doPost()"+"\n");

        connection = (Connection) request.getAttribute("db_connection");

        doUpdateUserSettings(request, response);

        connection = null;
    }

    // TODO do no update registered field (currently happens automatically due to UPDATE on schema

    public void doUpdateUserSettings(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("doUpdateUserSettings()");

        Document doc = (Document) getServletContext().getAttribute("request");

        /**
         * <?xml version="1.0" encoding="ISO-8859-1"?>
         <MFRequest>
         <Request type='SaveSettings' data=''/>
         <UserPrefs download_pref='../' email_pref='yes' open_on_download_pref='no' clear_uploads_pref='no' decompress_pref='no' password_pref='no'/>
         </MFRequest>
         */

        NodeList nList = doc.getElementsByTagName("UserPrefs");
        Node nNode = nList.item(0);
        Element eElement = (Element) nNode;

        String download_pref = eElement.getAttribute("download_pref");
        String email_pref = eElement.getAttribute("email_pref");
        String open_on_download_pref = eElement.getAttribute("open_on_download_pref");
        String clear_uploads_pref = eElement.getAttribute("clear_uploads_pref");
        String decompress_pref = eElement.getAttribute("decompress_pref");
        String password_pref = eElement.getAttribute("password_pref");
        String notification_address_pref = eElement.getAttribute("notification_address_pref");

        System.out.println("download_pref "+download_pref);

        // otherwise MySQL doesnt store backslashes, as they are escaped
        if(download_pref.indexOf("\\") > -1 ){
            System.out.println("Before ESCAPING Slashses for MySQL download_pref " +download_pref);
            download_pref = download_pref.replace("\\", "\\\\");
            System.out.println("After ESCAPING Slashses for MySQL download_pref " +download_pref);
        }

        // Already verified session is ok and user is logged in, see call to this method
        //int user = getUser((String) request.getSession().getAttribute("username"));
        int user = Integer.parseInt(request.getSession().getAttribute("userID").toString());

        // Remember to look at server log with SQL errors... a lot more detailed.
        /**
         *  +----+------+---------------------------+--------------+-----------+---------------+------------+
         | id | user | download_dir              | email_notify | auto_open | clear_uploads | decompress |
         +----+------+---------------------------+--------------+-----------+---------------+------------+
         |  1 |    1 | C:\Users\tchurton\Desktop | yes          | no        | no            | no         |
         +----+------+---------------------------+--------------+-----------+---------------+------------+


         */
        String SETTINGS_QUERY = "UPDATE mf_users_settings SET user="+user+", " +
                "download_dir='"+download_pref+"', " +
                "email_notify='"+email_pref+"', " +
                "auto_open='"+open_on_download_pref+"', " +
                "clear_uploads='"+clear_uploads_pref+"', " +
                "decompress='"+decompress_pref+"' " +
                "WHERE user="+user+";";
        /**
         * UPDATE mf_users_settings SET user=1, download_dir='../', email_notify='yes', auto_open='no', clear_uploads='yes', decompress='no' WHERE user=1;
         */

        int tmp1 = 0;
        int tmp2 = 0;

        System.out.println(SETTINGS_QUERY);

        try {
            //Class.forName("com.mysql.jdbc.Driver");  //registering the jdbc driver here

            //db_con = DriverManager.getConnection(db_url, db_user, db_pwd);
            Statement db_st = connection.createStatement();

            tmp1 = db_st.executeUpdate(SETTINGS_QUERY);

                /*
        +----+------+----------------------------------+---------------------+------------+-----------------------+
        | id | name | password                         | registered          | repository | email_address         |
        +----+------+----------------------------------+---------------------+------------+-----------------------+
        |  1 | Sam  | cc03e747a6afbbcbf8be7668acfebee5 | 2012-06-04 18:00:04 |          1 | sam.wootton@gmail.com |
        +----+------+----------------------------------+---------------------+------------+-------------------
        */

            if(password_pref != "" ){

                String PASSWORD_UPDATE_QUERY = "UPDATE mf_users SET password=MD5('"+password_pref+"') WHERE id="+user+";";
                System.out.println(PASSWORD_UPDATE_QUERY);

                tmp2 = db_st.executeUpdate(PASSWORD_UPDATE_QUERY);
            }

            if(notification_address_pref != "" ){

                String NOTIFICATION_ADDRESS_UPDATE_QUERY = "UPDATE mf_users SET email_address='"+notification_address_pref+"' WHERE id="+user+";";
                System.out.println(NOTIFICATION_ADDRESS_UPDATE_QUERY);

                tmp2 = db_st.executeUpdate(NOTIFICATION_ADDRESS_UPDATE_QUERY);

                // dont need. email is looked up when notification sent anyway
                // so doesnt need to be session data
                //request.getSession(false).setAttribute("userEmail", notification_address_pref);

            }

        }
            /*catch(ClassNotFoundException e1) {

                System.out.println(e1.getMessage());
                e1.printStackTrace();
            }*/
        catch (SQLException e2) {

            System.out.println(e2.getMessage());
            e2.printStackTrace();
        }


        String settingsChanged = tmp1==1 ? "yes" : "no";
        String passwordChanged = tmp2==1 ? "yes" : "no";


        StringBuilder strResp = new StringBuilder();
        strResp.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
        strResp.append("<MFResponse>\n");
        strResp.append("<Response type='SaveSettings' updatedSettings='"+settingsChanged+"' updatedPassword='"+passwordChanged+"'>\n");
        strResp.append("</Response>\n");
        strResp.append("</MFResponse>\n");

        response.setHeader("MFServer-Error", "false");

        write(response, strResp);
    }
}
